﻿import { BAR } from './chart/chartTypes'
export default function updateState(state, data) {

    //data: [ {title,headers,rows}]

    // extract statistic
    var { statistic } = state;
    if (!statistic) statistic = {};

    // set dataset
    var dataset, { dataset: oldSet } = statistic;
    if (oldSet) dataset = replaceRows(oldSet);
    else dataset = createDataset();

    // prepare defaults of statistic
    var { currentData = dataset[0], chartName = BAR } = statistic;

    return { ...state, statistic: { dataset, currentData, chartName } };

    function replaceRows(oldSet) {
        return oldSet.map((d, idx) => {
            return { ...d, rows: data[idx].rows }
        })
    }
    function createDataset() {
        return data.map(d => {
            var { title, headers: headerTexts, rows } = d;
            return {
                title,
                headers: headerTexts.map(text => ({ text })),
                rows,
                currentRow: 0,
                currentCol: 1
            }
        })
    }
}